import React, { Component } from 'react'
import {  DeviceEventEmitter, AsyncStorage, View, Text, StatusBar } from 'react-native'
import ReduxNavigation from '../Navigation/ReduxNavigation'
import AuthNavigation from '../Navigation/AuthNavigation'
import { connect } from 'react-redux'
//import StartupActions from '../Redux/StartupRedux'
import ReduxPersist from '../Config/ReduxPersist'
import { Loading } from '../Components'

// Styles
import styles from './Styles/RootContainerStyles'

class RootContainer extends Component {
  constructor(props) {
    super(props)
    this.state = {
      token: null,
      loading: true,
      isLogin: null,
    }
  }
  componentDidMount () {
    DeviceEventEmitter.addListener('login',(e)=>this.setState({isLogin:true}))
    DeviceEventEmitter.addListener('logout',(e)=>this.setState({isLogin:false}))
    // if redux persist is not active fire startup action
    if (!ReduxPersist.active) {
      this.props.startup()
    }
    AsyncStorage.getItem('token').then((token) => {
      if (token) {
        this.setState({token:token, loading:false, isLogin:true})
      } else {
        this.setState({loading:false, isLogin:false})
      }
    }).catch((error) => {
      console.error(error)
    })
  }
  componentWillUnmount() {
    DeviceEventEmitter.removeListener('login')
    DeviceEventEmitter.removeListener('logout')
  }

  render () {
    if (this.state.loading) {
      return <Loading />
    }
    return (
      <View style={styles.applicationView}>
        {this.state.isLogin ? (
          <ReduxNavigation />
        ) : (
          <AuthNavigation />
        )}
      </View>
    )
  }
}

const mapStateToProps = (state) => {
  return {
  }
}
// wraps dispatch to create nicer functions to call within our component
const mapDispatchToProps = (dispatch) => ({
  // startup: () => dispatch(StartupActions.startup())
})

export default connect(mapStateToProps, mapDispatchToProps)(RootContainer)
